<template>
  <div class="flex flex-col items-center bg-[#0a1a2f]/80 rounded-lg shadow-lg p-2 border border-[#00eaff]/30 backdrop-blur-md space-y-2">
    <div class="w-full text-center px-2 py-1 text-[#00eaff] text-xs font-medium border-b border-[#00eaff]/20">
      导入
    </div>
    
    <!-- GeoJSON导入 -->
    <div class="group relative w-9 h-9">
      <input
        type="file"
        accept=".geojson,.json"
        class="absolute inset-0 opacity-0 cursor-pointer z-10"
        @change="handleGeoJSONImport"
      />
      <div class="w-9 h-9 flex items-center justify-center rounded-lg bg-[#0a1a2f]/60 border border-[#00eaff]/20 hover:bg-[#1e3a5c]/80 hover:border-[#00eaff]/40 transition-all duration-200">
        <i class="fas fa-map text-lg text-[#00eaff]"></i>
      </div>
      <div class="absolute left-full ml-2 top-1/2 -translate-y-1/2 bg-[#0a1a2f] px-2 py-1 rounded text-xs text-[#00eaff] opacity-0 group-hover:opacity-100 transition-opacity duration-200 whitespace-nowrap z-20">
        导入GeoJSON
      </div>
    </div>

    <!-- TXT坐标导入 -->
    <div class="group relative w-9 h-9">
      <button
        class="w-9 h-9 flex items-center justify-center rounded-lg bg-[#0a1a2f]/60 border border-[#00eaff]/20 hover:bg-[#1e3a5c]/80 hover:border-[#00eaff]/40 transition-all duration-200"
        @click="showImportDialog = true"
      >
        <i class="fas fa-file-alt text-lg text-[#00eaff]"></i>
      </button>
      <div class="absolute left-full ml-2 top-1/2 -translate-y-1/2 bg-[#0a1a2f] px-2 py-1 rounded text-xs text-[#00eaff] opacity-0 group-hover:opacity-100 transition-opacity duration-200 whitespace-nowrap z-20">
        导入坐标文本
      </div>
    </div>
  </div>

  <!-- 导入对话框 -->
  <ImportDialog
    :show="showImportDialog"
    :onClose="() => showImportDialog = false"
    :onImport="handleTxtImport"
  />
</template>

<script setup>
import { ref } from 'vue'
import maplibregl from 'maplibre-gl'
import ImportDialog from './ImportDialog.vue'
import * as turf from '@turf/turf'

const props = defineProps({
  map: {
    type: Object,
    required: true
  }
})

const sourceCounter = ref(0)
const showImportDialog = ref(false)

// 导入的数据源ID计数器
const handleGeoJSONImport = async (event) => {
  const file = event.target.files?.[0]
  if (!file) return

  try {
    const text = await file.text()
    const geojson = JSON.parse(text)
    
    // 生成唯一的源ID和图层ID
    const sourceId = `imported-geojson-${sourceCounter.value}`
    const layerId = `${sourceId}-layer`
    sourceCounter.value++

    // 添加数据源
    props.map.addSource(sourceId, {
      type: 'geojson',
      data: geojson
    })

    // 根据GeoJSON的geometry类型添加适当的图层
    if (geojson.features?.[0]?.geometry?.type.includes('Point')) {
      // 点图层
      props.map.addLayer({
        id: layerId,
        type: 'circle',
        source: sourceId,
        paint: {
          'circle-radius': 6,
          'circle-color': '#00eaff',
          'circle-opacity': 0.8,
          'circle-stroke-width': 2,
          'circle-stroke-color': '#ffffff'
        }
      })
    } else if (geojson.features?.[0]?.geometry?.type.includes('LineString')) {
      // 线图层
      props.map.addLayer({
        id: layerId,
        type: 'line',
        source: sourceId,
        paint: {
          'line-color': '#00eaff',
          'line-width': 2,
          'line-opacity': 0.8
        }
      })
    } else {
      // 面图层
      props.map.addLayer({
        id: layerId,
        type: 'fill',
        source: sourceId,
        paint: {
          'fill-color': '#00eaff',
          'fill-opacity': 0.3,
          'fill-outline-color': '#00eaff'
        }
      })
    }

    // 缩放到数据范围
    const bounds = new maplibregl.LngLatBounds()
    geojson.features.forEach(feature => {
      if (feature.geometry.type === 'Point') {
        bounds.extend(feature.geometry.coordinates)
      } else if (feature.geometry.type === 'LineString') {
        feature.geometry.coordinates.forEach(coord => bounds.extend(coord))
      } else if (feature.geometry.type === 'Polygon') {
        feature.geometry.coordinates[0].forEach(coord => bounds.extend(coord))
      } else if (feature.geometry.type === 'MultiPolygon') {
        feature.geometry.coordinates.forEach(polygon => {
          polygon[0].forEach(coord => bounds.extend(coord))
        })
      }
    })
    
    if (!bounds.isEmpty()) {
      props.map.fitBounds(bounds, { 
        padding: 50,
        duration: 1000
      })
    }

  } catch (error) {
    console.error('Error importing GeoJSON:', error)
    alert('导入GeoJSON文件失败，请检查文件格式是否正确')
  }

  // 清除文件选择
  event.target.value = ''
}

// 计算长度（米）
const calculateLength = (coordinates) => {
  const line = turf.lineString(coordinates)
  return turf.length(line, { units: 'meters' })
}

// 计算面积（平方米）
const calculateArea = (coordinates) => {
  const polygon = turf.polygon([coordinates])
  return turf.area(polygon)
}

// 格式化长度
const formatLength = (meters) => {
  if (meters >= 1000) {
    return `${(meters / 1000).toFixed(2)} 千米`
  }
  return `${meters.toFixed(2)} 米`
}

// 格式化面积
const formatArea = (squareMeters) => {
  const mu = squareMeters / 666.67 // 1亩 = 666.67平方米
  return `${squareMeters.toFixed(2)} 平方米 (${mu.toFixed(2)} 亩)`
}

// 处理TXT文件导入
const handleTxtImport = async (file) => {
  if (!file) return

  try {
    const text = await file.text()
    const lines = text.split('\n').map(line => line.trim()).filter(line => line.length > 0)
    
    if (lines.length < 2) {
      throw new Error('文件内容不足')
    }

    // 读取类型标识
    const typeHeader = lines[0].toLowerCase()
    if (!['#point', '#line', '#polygon'].includes(typeHeader)) {
      throw new Error('无效的类型标识，请使用 #Point, #Line 或 #Polygon')
    }

    // 解析坐标
    const coordinates = lines.slice(1).map(line => {
      const [lng, lat] = line.split(/[,\s]+/).map(Number)
      if (isNaN(lng) || isNaN(lat)) {
        throw new Error('无效的坐标格式')
      }
      return [lng, lat]
    })

    // 生成图层ID
    const sourceId = `imported-txt-${sourceCounter.value}`
    const layerId = `${sourceId}-layer`
    sourceCounter.value++

    // 根据类型创建不同的图层
    let geometryType, paint, measurementInfo
    
    if (typeHeader === '#point') {
      geometryType = 'circle'
      paint = {
        'circle-radius': 6,
        'circle-color': '#00eaff',
        'circle-opacity': 0.8,
        'circle-stroke-width': 2,
        'circle-stroke-color': '#ffffff'
      }
    } else if (typeHeader === '#line') {
      geometryType = 'line'
      paint = {
        'line-color': '#00eaff',
        'line-width': 2,
        'line-opacity': 0.8
      }
      const length = calculateLength(coordinates)
      measurementInfo = `长度: ${formatLength(length)}`
    } else { // polygon
      geometryType = 'fill'
      paint = {
        'fill-color': '#00eaff',
        'fill-opacity': 0.3,
        'fill-outline-color': '#00eaff'
      }
      const area = calculateArea(coordinates)
      measurementInfo = `面积: ${formatArea(area)}`
    }

    // 添加数据源
    props.map.addSource(sourceId, {
      type: 'geojson',
      data: {
        type: 'Feature',
        geometry: {
          type: typeHeader === '#point' ? 'Point' : 
                typeHeader === '#line' ? 'LineString' : 'Polygon',
          coordinates: typeHeader === '#polygon' ? [coordinates] : coordinates
        },
        properties: {
          measurement: measurementInfo
        }
      }
    })

    // 添加图层
    props.map.addLayer({
      id: layerId,
      type: geometryType,
      source: sourceId,
      paint
    })

    // 如果有测量信息，显示弹窗
    if (measurementInfo) {
      const center = typeHeader === '#line' ? 
        coordinates[Math.floor(coordinates.length / 2)] :
        turf.center(props.map.getSource(sourceId)._data).geometry.coordinates

      new maplibregl.Popup()
        .setLngLat(center)
        .setHTML(`<div class="bg-[#0a1a2f]/90 text-[#00eaff] px-3 py-2 rounded border border-[#00eaff]/30">
          ${measurementInfo}
        </div>`)
        .addTo(props.map)
    }

    // 缩放到数据范围
    const bounds = new maplibregl.LngLatBounds()
    coordinates.forEach(coord => bounds.extend(coord))
    
    if (!bounds.isEmpty()) {
      props.map.fitBounds(bounds, { 
        padding: 50,
        duration: 1000
      })
    }

  } catch (error) {
    console.error('Error importing coordinates:', error)
    alert(error.message || '导入坐标文件失败，请检查文件格式是否正确')
  }
}
</script>

<style scoped>
.group:hover > div:last-child {
  opacity: 1;
}
</style> 